package com.tlx.util;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

/**
 * 通用工具类之按对象中某属性排序
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class SortUtils {
    public static final String DESC = "desc";
    public static final String ASC = "asc";

    /**
     * 对list中的元素按升序排列.
     * 
     * @param list
     *            排序集合
     * @param field
     *            排序字段
     * @return
     */
    public static List<?> sort(List<?> list, final String field) {
        return sort(list, field, null);
    }

    public static List<?> sort(List<?> list, final String field, final String sort) {
        Collections.sort(list, new Comparator() {
            public int compare(Object a, Object b) {
                try {
                    String av = BeanUtils.getProperty(a, field);
                    String bv = BeanUtils.getProperty(b, field);
                    if (sort != null && sort.toLowerCase().equals(DESC)) {
                        return bv.compareTo(av);
                    } else {
                        return av.compareTo(bv);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return list;
    }

}